package com.chen.palmar.project.agency;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.datasource.CommentRequest;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.utils.PicassoImageLoader;
import com.chen.palmar.common.widget.dialog.ShareDialog;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.BarChartView;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.entity.AgencyDetailEntity;
import com.chen.palmar.entity.CollectEntity;
import com.chen.palmar.project.home.InfoDetailActivity;
import com.primb.androidlibs.net.exception.ApiException;
import com.primb.androidlibs.ui.recyclerview.BaseQuickAdapter;
import com.primb.androidlibs.ui.recyclerview.BaseViewHolder;
import com.squareup.picasso.Picasso;

import java.util.Arrays;
import java.util.HashMap;

import butterknife.Bind;
import me.wangyuwei.flipshare.FlipShareView;
import me.wangyuwei.flipshare.ShareItem;
import rx.Subscription;


/**
 * @author Chen
 * @date 2018/1/3
 * 功能描述：经销商详情
 */

public class AgencyDetailActivity extends BaseActivity {
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.iv_top)
    ImageView ivTop;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.iv_agency_head)
    CircleImageView ivAgencyHead;
    @Bind(R.id.tv_agency_name)
    TextView tvAgencyName;
    @Bind(R.id.tv_agency_desc)
    TextView tvAgencyDesc;
    @Bind(R.id.tv_agency_user_name)
    TextView tvAgencyUserName;
    @Bind(R.id.tv_agency_user_phone)
    TextView tvAgencyUserPhone;
    @Bind(R.id.rv_agency_tag)
    RecyclerView rvAgencyTag;
    @Bind(R.id.tv_agency_brand)
    TextView tvAgencyBrand;
    @Bind(R.id.tv_agency_address)
    TextView tvAgencyAddress;
    @Bind(R.id.rv_agency_article)
    RecyclerView rvAgencyArticle;
    @Bind(R.id.seekBar)
    BarChartView seekBar;
    private BaseQuickAdapter<String, BaseViewHolder> adapterTag;
    private BaseQuickAdapter<AgencyDetailEntity.DataBean.ArticlesBean, BaseViewHolder> adapterArticle;
    private String distrId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {
        titleBar.setVisibility(View.INVISIBLE);
        toolBar.setNavigationOnClickListener(v -> AgencyDetailActivity.this.finish());
        toolBar.setBackgroundColor(ContextCompat.getColor(this, R.color.alpha));

        ivTop.setVisibility(View.VISIBLE);
        ivTop.setImageResource(R.mipmap.edit_icon);
        ivTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(distrId)) {
                    showPop(distrId);
                }
            }
        });
        ivTop.setTag(false);

        rvAgencyTag.setNestedScrollingEnabled(false);
        LinearLayoutManager layoutManager = new LinearLayoutManager(AgencyDetailActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvAgencyTag.setLayoutManager(layoutManager);
        adapterTag = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_agency_tag) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                helper.setText(R.id.iv_item_tag, item);
            }
        };
        rvAgencyTag.setItemAnimator(new DefaultItemAnimator());
        rvAgencyTag.setAdapter(adapterTag);

        rvAgencyArticle.setNestedScrollingEnabled(false);
        LinearLayoutManager manager = new LinearLayoutManager(AgencyDetailActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvAgencyArticle.setLayoutManager(manager);
        rvAgencyArticle.setItemAnimator(new DefaultItemAnimator());
        adapterArticle = new BaseQuickAdapter<AgencyDetailEntity.DataBean.ArticlesBean, BaseViewHolder>(R.layout.item_agency_detail) {
            @Override
            protected void convert(BaseViewHolder helper, AgencyDetailEntity.DataBean.ArticlesBean item) {
                helper.setText(R.id.tv_item_agency_good, item.getPraise_nums() + "");
                helper.setText(R.id.tv_item_agency_watch, item.getBrowse_nums() + "");
                helper.setText(R.id.tv_item_agency_location, TextUtils.isEmpty(item.getAddress_detail()) ? "" : item.getAddress_detail());
                helper.setText(R.id.tv_item_agency_content, TextUtils.isEmpty(item.getContent()) ? "" : item.getContent());
                helper.setText(R.id.tv_item_agency_name, TextUtils.isEmpty(item.getUser_name()) ? "" : item.getUser_name());
                helper.setText(R.id.tv_item_agency_date, TextUtils.isEmpty(item.getCreate_at()) ? "" : item.getCreate_at());

                CircleImageView head = (CircleImageView) helper.getView(R.id.iv_item_agency_head);
                if (!TextUtils.isEmpty(item.getUser_avatar())) {
                    Picasso.with(AgencyDetailActivity.this).load(item.getUser_avatar()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).into(head);
                }
            }
        };
        adapterArticle.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(AgencyDetailActivity.this, InfoDetailActivity.class);
                intent.putExtra("info", adapterArticle.getData().get(position).getArticleId() + "");
                startActivity(intent);
            }
        });
        rvAgencyArticle.setAdapter(adapterArticle);


        PicassoImageLoader.displayImage(AgencyDetailActivity.this, ivAgencyHead, R.mipmap.home_item_head_icon, 0);

        String info = getIntent().getStringExtra("info");

        try {
            getDataForWeb(info);
        } catch (Exception e) {
            e.printStackTrace();
            showToast("服务器数据格式异常");
        }
    }

    private void getDataForWeb(String disrtId) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        map.put("disrtId", disrtId);
        Subscription subscribe = DataCenter.agencyDetailInfo(map).subscribe(new HttpSubscriber<AgencyDetailEntity>(this, showLoading("加载中")) {

            @Override
            public void onNext(AgencyDetailEntity agencyDetialEntity) {
                AgencyDetailEntity.DataBean data = agencyDetialEntity.getData();
                if (null == data) {
                    showToast("服务器返回数据为空");
                    return;
                }
                if (!TextUtils.isEmpty(data.getLogo())) {
                    PicassoImageLoader.displayImage(AgencyDetailActivity.this, ivAgencyHead, data.getLogo(), 2);
                }
                tvAgencyAddress.setText(data.getAddress_name());
                tvAgencyBrand.setText(data.getBrand());
                tvAgencyDesc.setText(data.getDesc());
                tvAgencyName.setText(data.getName());
                tvAgencyUserName.setText(data.getContacts());
                tvAgencyUserPhone.setText(data.getMobile());

                if (TextUtils.isEmpty(data.getChannel())) {
                    rvAgencyTag.setVisibility(View.GONE);
                } else {
                    rvAgencyTag.setVisibility(View.VISIBLE);
                    adapterTag.setNewData(Arrays.asList(data.getChannel().split(" ")));
                }
                adapterArticle.setNewData(data.getArticles());

                float value = ((float) data.getRation_num()) / ((float) (data.getBulk_num() + data.getRation_num()));

                seekBar.setProgress(value);

                distrId = data.getDistrId() + "";

                ivTop.setTag(data.getFavoriteStatus() == 1);
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_agency_detail;
    }

    private void showPop(String distrId) {
        int color = ContextCompat.getColor(this, R.color.app_font);
        FlipShareView share = new FlipShareView.Builder(this, ivTop).addItem(new ShareItem("收藏", color, Color.WHITE)).addItem(new ShareItem("分享", color, Color.WHITE)).setBackgroundColor(0x60000000).setItemDuration(500).setSeparateLineColor(ContextCompat.getColor(this, R.color.app_main_gray)).setAnimType(FlipShareView.TYPE_SLIDE).create();
        share.setOnFlipClickListener(new FlipShareView.OnFlipClickListener() {
            @Override
            public void onItemClick(int position) {
                if (position == 0) {
                    collectInfo(((boolean) ivTop.getTag()), distrId);
                } else if (position == 1) {
                    share(distrId);
                }
            }

            @Override
            public void dismiss() {

            }
        });
    }

    private void share(String info) {
        ShareDialog shareDialog = new ShareDialog();
        shareDialog.setRef_id(info);
        shareDialog.setRef_type("3");
        shareDialog.show(getSupportFragmentManager());
    }

    /**
     * 收藏
     *
     * @param tag
     */
    private void collectInfo(boolean tag, String id) {
        CommentRequest.collectInfo(id, "2", tag, new CommentRequest.OnLoadSuccessListener<CollectEntity>() {
            @Override
            public void onSuccess(CollectEntity entity) {
                if (!TextUtils.isEmpty(entity.getMessage())) {
                    showToast(entity.getMessage());
                    ivTop.setTag(!tag);
                }
            }

            @Override
            public void onFailure(ApiException e) {
                if ("已收藏，请勿重复收藏".equals(e.getMessage())) {
                    ivTop.setTag(!tag);
                }
            }
        });
    }
}
